﻿using Microsoft.Extensions.Configuration;
using ReadWriteIsolate.Model;
using System;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;

namespace ReadWriteIsolate.DB
{
    public class SQLHelper
    {
        public readonly IConfiguration _configuration;

        public SQLHelper(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public T Find<T>(int id) where T : BaseModel //能保证传递进来的一定是数据库的表实体
        {
            Type type = typeof(T);
            string columnString = string.Join(",", type.GetProperties().Select(p => $"[{p.Name}]"));
            string sql = $@"select {columnString} from [{type.Name}] where id=@id";

            SqlParameter[] parameters = new SqlParameter[]
            {
                new SqlParameter("@id",id),
            };

            String connStr = SqlConnectionStringPool.GetConnectionString(SqlConnectionStringPool.ConnectionType.Read);
            Console.WriteLine(connStr);
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddRange(parameters);
                using (var reader = cmd.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        T t = Activator.CreateInstance<T>();
                        foreach (var prop in type.GetProperties())
                        {
                            prop.SetValue(t, reader[prop.Name] is DBNull ? null : reader[prop.Name]);
                        }

                        return t;
                    }
                    else
                    {
                        return default(T);
                    }
                }
            }
        }


        public async Task<bool> Insert(String sql, params SqlParameter[] parameters)
        {
            String connStr = SqlConnectionStringPool.GetConnectionString(SqlConnectionStringPool.ConnectionType.Write);
            Console.WriteLine(connStr);
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddRange(parameters);
                return await cmd.ExecuteNonQueryAsync() == 1;
            }
        }

    }
}
